<template>
  <div class="page-content">
    <div class="text-right" v-if="view">
      <el-button size="small" class="mb-2 d-print-none" @click="handlePrint">
        <i class="fa fa-print"></i>
        打印
      </el-button>
    </div>
    <div :id="printId" class="p-5 border-noprint">
      <div class="body-panel" v-loading="loading">
        <p class="body-text">
          {{ data.gua_org_name_short }}（意向）函字
          <span class="text-decoration">[{{ data.letter_word_no || '-' }}]</span>
          第
          <span class="text-decoration">{{ data.letter_number_no || '-' }}</span>
          号
        </p>
        <h4 class="text-center">担保意向函</h4>
        <p class="body-text">
          <span class="text-decoration">{{ relatedData.bank_name }}：</span>
        </p>
        <div class="text-indent">
          就申请人
          <span class="text-decoration">{{ replayName }}</span>
          向贵行申请人民币
          <span class="text-decoration">{{ total }}</span>
          、期限为
          <span class="text-decoration">{{ year }}年</span>
          的贷款业务事宜， 我公司拟对申请人所申请的上述信贷融资业务及债务金额的
          <span v-if="!view" class="d-inline-flex input-td">
            <input
              v-model="data.bear_rate"
              v-input-number="{ min: 0, fixed: 3 }"
              placeholder="请输入"
              style="width: 100px"
              class="m-0 form-control"
            />
            %
          </span>
          <span v-else class="text-decoration">{{ data.bear_rate }}%</span>
          限提供担保。
        </div>
        <p class="text-indent">
          本意向函仅为业务洽谈之函，最终是否担保及担保金额、担保期限、担保方式等以我公司与贵行签订的担保合同为准。本意向函有效期为60日。
        </p>
        <div class="body-write">
          <p class="pt-5">
            <span v-if="view || isSelfProject">{{ data.gua_company || '-' }}</span>
            <c-select
              :options="agencies"
              v-else
              :props="{ value: 'client_id', label: 'org_name' }"
              v-model="data.gua_org_id"
              style="width: 250px"
              @change="handleAgencySelect"
            ></c-select>
          </p>
          <p>负责人或授权代理人(签字)：{{ data.gua_company_sign }}</p>
          <p class="bottm-time">
            <span v-if="view">{{ $utils.dateFormat(data.letter_date, 'yyyy年MM月dd日') }}</span>
            <span v-else>{{ $utils.dateFormat(new Date(), 'yyyy年MM月dd日') }}</span>
          </p>
        </div>
      </div>
    </div>
    <div class="pt-2 text-center">
      <el-button type="primary" v-if="!view" @click="sendLetter">确认发送</el-button>
    </div>
  </div>
</template>
<script>
import { mapGetters } from 'vuex'
import { printA4, nzhToMoney } from '@vimi/utils-tool'

export default {
  components: {},
  props: {
    isView: Boolean,
    relatedData: {
      type: Object,
      default() {
        return {}
      },
    },
  },
  data() {
    return {
      loading: false,
      data: {},
      agencies: [],
      tableName: 'ele_letter_info',
    }
  },
  computed: {
    ...mapGetters(['user', 'clientId']),
    replayName() {
      if (+this.relatedData.customer_type === 2) {
        return this.relatedData.corp_name || this.relatedData.corp_name
      } else {
        return `${this.relatedData.customer_name}(负责人：${
          this.relatedData.corp_name || this.relatedData.corp_name
        })`
      }
    },
    // queryAddressCode() {
    //   return this.user.queryAddressCode || this.user.addressCode
    // },
    // orgRegionLever() {
    //   return this.user.orgRegionLever
    // },
    printId() {
      return `print-letter-${this.relatedData.customer_related_id}`
    },
    total() {
      const num =
        this.relatedData.res_funds ||
        this.relatedData.bank_approved_funds ||
        this.relatedData.apply_funds
      return nzhToMoney(num * 10000)
    },
    isUserTown() {
      return this.user.orgRegionLever === 3
    },
    year() {
      const num = this.relatedData.approval_load_years || this.relatedData.load_years
      const text = nzhToMoney(num)
        .replace('元', '')
        .replace('整', '')
        .replace('角', '月')
        .replace('分', '')
      return text
    },
    view() {
      return this.isView || +this.relatedData.ele_letter_status > 1
    },
    isSelfProject() {
      return +this.relatedData.gua_type === 2
    },
  },
  watch: {
    relatedData: {
      handler: function () {
        this.getData()
        if (this.isSelfProject || this.isUserTown) {
          this.getAgencyByAddressCode()
        } else {
          this.getAgencyByClientId()
        }
      },
      deep: true,
    },
  },
  created() {
    if (!this.isSelfProject || this.isUserTown) {
      this.getAgencyByAddressCode()
    } else {
      this.getAgencyByClientId()
    }
  },
  methods: {
    getData() {
      const params = {
        'customer_related_id.eq': this.relatedData.customer_related_id,
        'ele_letter_type.eq': 1,
      }
      this.loading = true
      this.$api
        .getData(this.$serviceName, this.tableName, params)
        .then(res => {
          this.data = (res && res.data && res.data[0]) || {}
          if (!this.data.gua_company) {
            this.handleAgencySelect(this.clientId)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    sendLetter() {
      if (!this.data.bear_rate) {
        return this.$message.warning('请输入风险比例')
      }
      if (!this.data.gua_org_id) {
        return this.$message.warning('请选择担保公司')
      }
      this.data.customer_related_id = this.relatedData.customer_related_id
      this.data.letter_date = this.$utils.dateFormat(new Date(), 'yyyy-MM-dd')
      this.data.bank_name = this.relatedData.bank_name
      this.data.ele_letter_type = 1
      this.$utils
        .msgbox({
          message: `确定发送此担保意向函?`,
          type: 'info',
          beforeClose: () => this.submit(),
        })
        .then(() => {
          this.$message.success('发送成功！')
          this.$emit('success', false)
        })
        .catch(() => this.$message.error(`发送失败，请重试！`))
    },
    submit() {
      if (this.data.ele_letter_info_id) {
        const data = {
          bank_name: this.relatedData.bank_name,
          letter_date: this.$utils.dateFormat(new Date(), 'yyyy-MM-dd'),
          gua_org_name_short: this.data.gua_org_name_short,
          gua_org_code: this.data.gua_org_code,
          gua_company_sign: this.data.gua_company_sign,
          bear_rate: this.data.bear_rate,
          gua_company: this.data.gua_company,
        }
        return this.$api.updateData(
          this.$serviceName,
          this.tableName,
          this.data.ele_letter_info_id,
          data
        )
      } else {
        return this.$api.addData(this.$serviceName, this.tableName, this.data)
      }
    },
    handleAgencySelect(value) {
      const agency = this.agencies.find(item => item.client_id === value) || {}
      this.$set(this.data, 'gua_org_id', agency.client_id)
      this.$set(this.data, 'gua_org_name_short', agency.org_name_short)
      this.$set(this.data, 'gua_org_code', agency.org_code)
      this.$set(this.data, 'gua_company_sign', agency.corp_name)
      this.$set(this.data, 'gua_company', agency.org_name)
    },
    async getAgencyByAddressCode() {
      // 2020.4.20 市农担和省农担只能选择自身 区县可以选择自身和联担对象
      const params = {
        'orWhere.client_id.eq': [this.clientId, this.relatedData.recommend_service],
      }

      await this.getAgencyByParams(params)
      this.getData()
    },
    async getAgencyByClientId() {
      await this.getAgencyByParams({
        'client_id.eq': this.clientId,
      })
      this.getData()
    },
    async getAgencyByParams(params) {
      this.agencyLoading = true
      const [res] = await this.$utils.promise(
        this.$api.getData(this.$serviceName, 'credit_select_view', params, {
          N1address_code: 'asc',
        })
      )
      this.agencyLoading = false
      this.agencies = (res && res.data) || []
    },
    handlePrint() {
      printA4(
        document.getElementById(this.printId).innerHTML,
        `
        body {font-family: SimSun;}
        .text-indent{text-indent: 2rem;}
        .text-decoration{border-bottom: 1px solid;}
        .body-write {text-align: right;}
        .page-content {max-width: 794px;margin: 0 auto;font-size: 1.2rem;line-height: 2;}
      `
      )
    },
  },
}
</script>
<style lang="scss" scoped>
.page-content {
  max-width: 700px;
  margin: 0 auto;
  font-size: 1.2rem;
  line-height: 2;
}
.body-text {
  font-size: 1.2rem;
}
.text-indent {
  text-indent: 2.4rem;
}
.text-decoration {
  border-bottom: 1px solid;
}
.body-write {
  text-align: right;
}
.border-noprint {
  border: 1px solid $border-color;
}
</style>
